from app import create_app
from app.extensions import db
from flask_script import Manager, Server
from flask_migrate import MigrateCommand
from app.models import AvgMoneyCity, importSqlFile,District,Job
import os

# 配置运行环境
config_name = os.environ.get('FLASK_CONFIG') or 'default'

# 创建app
app = create_app(config_name)

# app放在Manage下管理
manage = Manager(app)

# 增加运行参数选择
manage.add_command("runserver", Server(port=5000, use_debugger=True, host='0.0.0.0'))
manage.add_command("runserver2", Server(port=8080, use_debugger=True))

manage.add_command("db", MigrateCommand)

if __name__ == '__main__':
    # 配置自动创建表
    with manage.app.app_context():
        # 删除全部实体类表
        # db.drop_all()
        # 创建实体类表
        db.create_all()
        db_session = db.session
        # 初始化时添加数据
        db_session.add_all([
            AvgMoneyCity(city='重庆', avg_money="3500"),
            AvgMoneyCity(city='上海', avg_money="8000"),
            AvgMoneyCity(city='四川', avg_money="6500"),
            AvgMoneyCity(city='深圳', avg_money="6000"),
            AvgMoneyCity(city='厦门', avg_money="7000")
        ])
        # 结束记得提交,数据才能保存在数据库中
        db_session.commit()
        # 关闭会话
        db_session.close()

    sql_files = {
        District: 'district.sql',
       Job: 'job.sql'
    }
    for entity,sql_file in sql_files.items():

        list = []

        if len(entity.query.all()) ==0:
            # 初始化加入脚本语句
            importSqlFile("app/config/" + sql_file, db_session)

    manage.run()
